package huffman;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class DataInputStreamEx {
	private DataInputStream dis;
	private BitBuffer buffer =  new BitBuffer(8);
	public int available() throws IOException {
		return (dis.available() * 8) + buffer.size();
	}
	public Boolean readBit() throws IOException {
		if(buffer.size() == 0 && dis.available() > 0) {
			buffer.add(dis.readByte());
		}
//		if(available() % 8 == 0 && available() > 0) {
//			buffer.clear();
//			buffer.add(dis.readByte());
//		}
		return buffer.poll();
	}
	
	public Byte readByte() throws IOException {
		BitBuffer bfex = new BitBuffer(8);
		while(bfex.remainingCapacity() != 0) {
			bfex.add(readBit());
		}
		return bfex.toByte();
	}
	public DataInputStreamEx(FileInputStream s) throws IOException {
		dis = new DataInputStream(s);
		s.getChannel().position(0);
		
	}
	public Integer readInt() throws IOException {
		BitBuffer bfex = new BitBuffer(32);
		while(bfex.remainingCapacity() != 0) {
			bfex.add(readBit());
		}
		return bfex.toInteger();
	}

	public boolean[] readArray(int size) throws IOException {
		boolean array[] = new boolean[size];
		int i = 0;
		while(this.available() > 0) {
			array[i] = readBit();
		}
		return array;
	}
}
